$(function() {

	var curItem = 0; // 当前环节，初始化时为0

	var curStep;

	var items;

	var startLeftValue;

	var itemLong;

	var startResult;

	var leftValue;

	var halfLong;

	var marginRight;

	var result;

	var eventId = $('#eventId').text();

	// var buzy = 0;

	var boxLength = 0; // 环节数

	var hasReload = 1; // 是否重新载入该页面

	var free = 1; // 是否处于空闲（按下一环节、增环节者视为指挥长，在不刷新页面下free永入变为0）

	loadLogStep();

	setInterval(function() {
		if (free == 1) {
			loadLogStep();
		}
	}, 5000);

	function loadLogStep() {
		var timestamp = Date.parse(new Date());
		url = "/ag/zrt/findAll_LogStep.action?ts="+timestamp; /* 加载环节 */
		data = {
			eventId : eventId
		};
		$.ajax( {
			url : url,
			data : data,
			success : ifUpdate
		});
	}

	function nextStep() {

		$(parent.window.frames['main'].document).find('#nextStep').click(
				function() {
					// alert(eventId);
					// buzy = 1;
					$(parent.window.frames['main'].document).find('#nextStep')
							.attr("disabled", true);
					$(parent.window.frames['main'].document).find('#send')
					.attr("disabled", true);
					free = 0;
					curItem += 1;
					if ($(curStep).next().attr('class') == "item") {
						var newCurStepId = $('.currentStep').next().attr('id');// 新当前环节ID
						updateCurrentStepNumAndCurrentStepId(eventId,
								newCurStepId); // 更新当前环节序号
						itemLong = 300;
						result = parseInt(result, 10) - parseInt(itemLong, 10)
								/ 2 - parseInt(marginRight, 10); // 算出向左缩进的距离
						// alert(result);
						$('.container').animate( { // 动态向左缩进
									left : result + 'px'
								}, 500);
						$(curStep).next().animate( { // 动态变大
									fontSize : '150%',
									height : '70px',
									width : '300px'
								}, 200).addClass('currentStep itemOverFlow');
						$(curStep).animate( { // 动态回愎
									fontSize : '100%',
									height : '50px',
									width : '150px'
								}, 200).removeClass(
								'currentStep curItem itemOverFlow');

						$(curStep).next().click(function() {
							alert("cool");
						});

						var oldCurStepId = $('.currentStep').prev().attr('id');// 上一当前环节ID
						// alert(oldCurStepId);
						createEndTime(oldCurStepId);// 记录结束当前环节的当前时间

						$(curStep).unbind('click');
						curStep = $(curStep).next();

						var newCurStepId = $('.currentStep').attr('id');// 新当前环节ID
						// alert(newCurStepId);
						createStartTime(newCurStepId); // 记录新当前步骤开始时间
						// updateCurrentStepId(newCurStepId);
					}
					// buzy = 0;
					setTimeout(function() {
						$(parent.window.frames['main'].document).find('#nextStep').attr("disabled", false);
					}, 2000);

				});
//		$(parent.window.frames['main'].document).find('#nextStep').attr(
//				"disabled", false);
	}

	function ifUpdate(data) {
		if (curItem == 0) {
			curItem = data.curStepNum;// 设置当前环节
			boxLength = data.stepList.length;
			// alert(curItem);
			// alert(boxLength);
			showStep(data);
		} else {
			// alert(curItem +" 当前环节 "+ data.curStepNum);
			// alert(boxLength +" 环节数 "+ data.stepList.length);
			if (curItem != data.curStepNum || boxLength != data.stepList.length) {
				// $(parent.window.frames['main'].document).find('#maxTime').text("0");
				curItem = data.curStepNum;
				boxLength = data.stepList.length;
				showStep(data);
			}
		}
	}

	function showStep(data) {
		// buzy = 1; // 忙状态
		// curItem = data.curStepNum;// 设置当前环节
		// alert(curItem);
		$('.container').empty();
		var stepNum = 0; // 步骤计数器
		var step = null;

		/*
		 * 找到头结点
		 */
		$.each(data.stepList, function(i, info) {
			if (info.a == "1") {
				step = info;
				// alert(step.psId);
				// alert(step.tbLogPlanStep.psId);
				stepNum += 1;
				eventId = info.tbEvent.EId;
				fillIntoHtml(info.psId, info.psName, info.tbEvent.EId);
				return false;
			}
		});

		/*
		 * 找出后续结点
		 */
		// alert(stepNum);
		while (stepNum < data.stepList.length) {
			// alert("enter while");
			$.each(data.stepList, function(i, info) {
				// alert(info.psId+" and "+step.tbLogPlanStep.psId);
					if (info.psId == step.tbLogPlanStep.psId) {
						step = info;
						stepNum += 1;
						fillIntoHtml(info.psId, info.psName, info.psContent);
						return false;
					}
				});
		}

		afterLoading();
		// buzy = 0;
	}

	function fillIntoHtml(id, name, eventId) {
		var shtml = "<div class='item' id = " + id + " name=" + eventId + ">"
				+ name + "</div>";
		$('.container').append(shtml);
	}

	/* 加载完环节后执行 */
	function afterLoading() {

		items = $(".container div").length; // 取得环节数
		if (items != 0) {
			// curItem = 1; // 起始环节序号
			// alert(curItem+"cool");
			curStep = $(".container div").eq(curItem - 1); // 取得当前环节

			$(".container div").eq(curItem - 1).addClass( // 设置当前环节样式
					"curItem currentStep itemOverFlow");

			itemLong = $(".container div").eq(0).css("width");// 取得环节框长
			if (hasReload == 1) {
				halfLong = $('.container').css('left');// 取得最初始左边空间
				hasReload = 0;
			}
			leftValue = halfLong;
			// alert(leftValue);
			marginRight = $('.container div').eq(0).css('margin-right');
			if (curItem == 1) {
				result = parseInt(leftValue, 10) - 150; // 算出向左缩进的距离
			} else {
				result = parseInt(leftValue, 10) - 150 - (curItem - 1)
						* (parseInt(itemLong, 10) + parseInt(marginRight, 10)); // 算出向左缩进的距离
			}
			// alert(result, 10);
			$(".container").css("left", result + 'px'); // 设置居中

			// $('.item').eq(curItem - 1).click(function() {
			// alert("cool");
			// });

			var curStepId = $('.currentStep').attr('id');

			// alert(curStepId);
			updateCurrentStepId(curStepId);
			createStartTime(curStepId);// 开始当前环节的时间

			window.setTimeout(nextStep, 500); // 防止加载时间差导致下一环节按钮失效
			window.setTimeout(addNewStep, 500); // 防止加载时间差导致增加环节按钮失效
			window.setTimeout(finishButton, 2000); // 防止加载时间差导致增加环节按钮失效

			// alert(result);
		}
	}
	/* 更新当前环节序号和当前环节ID */
	function updateCurrentStepNumAndCurrentStepId(eventId, currentStepId) {
		var timestamp = Date.parse(new Date());
		var data = {
			eventId : eventId,
			currentStepId : currentStepId
		};
		$
				.ajax( {
					url : "/ag/zrt/updateCurrentStepNumAndCurrentStepId_CurrentEvent.action?ts="+timestamp,
					type : "POST",
					data : data,
					success : function(data) {
						// alert(data.updateSucc);
					buzy = 0;
				}
				});
	}

	/* 打开增加环节窗口 */
	function addNewStep() {
		$(parent.window.frames['main'].document).find('#addStep').click(
				function() {
					free = 0;
					ifAddOpener = 1;
					window
							.open("/ag/zhh/chat/addStep.jsp?curStepId="
									+ $('.currentStep').attr('id')
									+ "&eventId=" + eventId, null,
									"scrollbars = yes,resizable = yes");
				});
//		$(parent.window.frames['main'].document).find('#addStep').attr(
//				"disabled", false);
	}
	/*
	 * 创建进入某环节的开始时间
	 */
	function createStartTime(curStepId) {
		var timestamp = Date.parse(new Date());
		var url = "/ag/zrt/createStartTime_LogStep.action?ts="+timestamp;
		var data = {
			curStepId : curStepId,
			eventId : eventId
		};

		$.ajax( {
			url : url,
			data : data,
			type : "POST",
			success : function(data) {
			}
		});
	}
	/*
	 * 创建离开某环节的结束时间
	 */
	function createEndTime(curStepId) {
		var timestamp = Date.parse(new Date());
		var url = "/ag/zrt/createEndTime_LogStep.action?ts="+timestamp;
		var data = {
			curStepId : curStepId,
			eventId : eventId
		};

		$.ajax( {
			url : url,
			data : data,
			type : "POST",
			success : function(data) {
			}
		});
	}
	/*
	 * 更新当前事件表中保存的当前环节ID
	 */
	function updateCurrentStepId(currentStepId) {
		var timestamp = Date.parse(new Date());
		var url = "/ag/zrt/updateCurrentStepId_CurrentEvent.action?ts="+timestamp;
		var data = {
			currentStepId : currentStepId,
			eventId : eventId
		};

		$.ajax( {
			url : url,
			data : data,
			type : "POST",
			success : function() {
			}
		});
	}

	// setInterval(checkReload, 5000);
	// checkReload();
	function checkReload() {
		// alert(buzy);
		// if (buzy == 0) {
		window.location.reload();
		// }

	}

	function finishButton() {
		$(parent.window.frames['main'].document).find('#finishProcessing')
				.click(fininshProcessing);
	}

	function fininshProcessing() {
		var lastStepId = $('.currentStep').attr('id');// 最后环节ID
		// alert(lastStepId);
		createEndTime(lastStepId);// 记录结束当前环节的当前时间
		var timestamp = Date.parse(new Date());
		var url = "/ag/do/endProcessingEvent_processEventEndByPlan.action?ts="+timestamp;
		// var data = {};
		// alert("do");
		$.post(url, {}, function(data) {
			// alert("done");
				parent.parent.window.location.href = "/ag/index.jsp"
			});

		// alert("done");

	}

	// window.setTimeout(nextStep, 1000); // 防止加载时间差导致下一环节按钮失效
	// window.setTimeout(addNewStep, 1000); // 防止加载时间差导致增加环节按钮失效

});
